package com.googlecode.gwtbb.client.only.widget.display.forum;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.gwtbb.client.only.glue.PathUtils;
import com.googlecode.gwtbb.client.only.glue.TokenOwner;
import com.googlecode.gwtbb.client.only.glue.events.GwtbbEvents;
import com.googlecode.gwtbb.client.only.remote.ClientSession;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 21, 2008
 */
public class GwtbbBody extends Composite implements TokenOwner {
	private SimplePanel mainPanel;
	private ForumList forumList;
	private ForumDetail forumDetail;
	private ThreadDetail threadDetail;
	private String fragmentStart;

	public GwtbbBody(ClientSession session, String fragmentStart) {
		this.fragmentStart = fragmentStart;

		mainPanel = new SimplePanel();
		initWidget(mainPanel);

		forumDetail = new ForumDetail(session);
		GwtbbEvents.instance().addPostEventListener(forumDetail);
		threadDetail = new ThreadDetail(session);

		forumList = new ForumList(session);
		mainPanel.setWidget(forumList);
		GwtbbEvents.instance().addUserAuthenticationEventListener(forumList);
		GwtbbEvents.instance().addForumEventListener(forumList);
	}

	public String getFragmentStart() {
		return fragmentStart;
	}

	public void setFragmentStart(String fragmentStart) {
		this.fragmentStart = fragmentStart;
	}

	public boolean owns(String fragment) {
		return fragment != null && fragment.startsWith(getFragmentStart());
	}

	public void serve(String token) {
		token = PathUtils.getSubToken(token);
		TokenOwner subOwner;
		if (threadDetail.owns(token)) {
			subOwner = threadDetail;
		} else if (forumDetail.owns(token)) {
			subOwner = forumDetail;
		} else {
			subOwner = forumList;
		}
		mainPanel.setWidget((Widget)subOwner);
		subOwner.serve(token);
	}
}
